<template>
	<!-- 商品-商品规格 -->
	<div>
		<Card :bordered="false" dis-hover class="ivu-mts">
			<div class="new_card_pd">
				<!-- 筛选条件 -->
				<Form inline ref="artFrom" :model="artFrom" :label-width="labelWidth" :label-position="labelPosition"
					class="tabform" @submit.native.prevent>
					<Row :gutter="24" type="flex" justify="end">
						<Col span="24" class="ivu-text-left">
						<FormItem :label="$t('page.product.SKU')+'：'">
							<Input v-model="artFrom.no" :placeholder="$t('page.product.input_sku')"
								class="input-add"></Input>
						</FormItem>
						<FormItem :label="$t('page.stock.date')+'：'">
							<DatePicker type="date" @on-change="onchangeOff" :options="endPickOptions" :value="timeVal"
								v-model="timeVal" :placeholder="$t('page.stock.select_date')" format="yyyy-MM-dd"
								style="width: 260px;">
							</DatePicker>
						</FormItem>
						<!-- <FormItem label="供应商：" prop="pid" label-for="pid">
							<Select v-model="artFrom.supplier_id" clearable class="input-add" filterable>
								<Option v-for="item in supplierList" :value="item.id" :key="item.id">{{ item.supplier_name }}</Option>
							</Select>
						</FormItem> -->
						<FormItem label="供应商：" prop="pid" label-for="pid">
							<Select v-model="artFrom.code" clearable class="input-add" filterable>
								<Option v-for="item in supplierList" :value="item.code" :key="item.code">{{item.code}}--{{ item.supplier_name }}</Option>
							</Select>
						</FormItem>
						<FormItem :label="$t('page.stock.warehouse')+'：'">
							<Select v-model="artFrom.warehouse_name" clearable style="width:200px;">
								<Option v-for="item in stockNameList" :value="item.value" :key="item.value">
									{{ item.label }}
								</Option>
							</Select>
							<Button type="primary" @click="userSearchs"
								class="ml10">{{$t('page.stock.search')}}</Button>
							<Button type="primary" @click="exportStock"
								class="ml10">{{$t('page.stock.export')}}</Button>
						</FormItem>
						</Col>
					</Row>
				</Form>
			</div>
		</Card>
		<!-- 相关操作 -->
		<Card :bordered="false" dis-hover class="ivu-mt">
			<!-- 商品规格表格 -->
			<Table class="mt25" ref="selection" :columns="columns4" :data="tableList" :loading="loading" height="500"
				highlight-row :no-data-text="$t('page.product.no_data')"
				:no-filtered-data-text="$t('page.product.no_filtering')">

				<template slot-scope="{ row, index }" slot="created_at">
					{{ formatTimeNative(row.created_at) }} <!-- 调用格式化方法 -->
				</template>
				<!-- <template slot-scope="{ row, index }" slot="action">
          <a v-if="row.status == 1" @click="edit(row)">编辑</a>
          <Divider v-if="row.status == 1" type="vertical" />
          <a @click="del(row, '删除规格', index)">删除</a>
        </template> -->
			</Table>
			<div class="acea-row row-right page">
				<Page :total="total" :current="artFrom.page" @on-change="pageChange" :page-size="artFrom.limit" />
			</div>
		</Card>
	</div>
</template>

<script>
	import {
		mapState
	} from "vuex";
	import {
		packageStockListApi,
		exportPackageStockList
	} from "../../../api/product.js";
	
	import * as productApi from "@/api/product";
	import {
		getNoPageSupplierProductList
	} from "@/api/supplier";
	import {
		log
	} from "vxe-table";
	export default {
		name: "productAttr",
		data() {
			return {
				loading: false,
				timeVal: 0,
				artFrom: {
					page: 1,
					limit: 10,
					supplier_id: "",
					status: 0,
					code:"",
					no: "",
					date: "",
				},
				supplierList: [],
				stockNameList: [{
						value: '1791498718751334401',
						label: 'CA5005'
					},
					{
						value: '101816795504',
						label: 'Houston'
					}
				],

				tableList: [],
				total: 0
			};
		},
		computed: {
			...mapState("admin/layout", ["isMobile"]),
			...mapState("admin/order", ["orderChartType"]),
			labelWidth() {
				return this.isMobile ? undefined : 80;
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
			columns4() {
				return [{
						title: $t('page.product.SKU'),
						key: "sku",
						width: 180,
					},
					{
						title: $t('page.stock.stock'),
						key: "stock",
						minWidth: 80,
					},
					{
						title: $t('page.stock.one_field'),
						key: "one_field",
						minWidth: 80,
					},
					{
						title: $t('page.stock.two_field'),
						key: "two_field",
						minWidth: 80,
					},
					{
						title: $t('page.stock.three_field'),
						key: "three_field",
						minWidth: 80,
					},
					{
						title: $t('page.stock.four_field'),
						key: "four_field",
						minWidth: 80,
					},
					{
						title: $t('page.stock.five_field'),
						key: "five_field",
						minWidth: 80,
					},

				]
			}
		},
		created() {
			this.getDataList();
		},
		mounted() {
			this.getSupplierList();
		},
		methods: {
			//获取供应商列表；
			getSupplierList() {
				getNoPageSupplierProductList()
					.then(async (res) => {
						this.supplierList = res.data.info;
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			// 具体日期
			onchangeTime(e) {
				this.artFrom.date = this.timeVal
				this.orderData.page = 1;
				this.allReset();
				this.getDataList();
			},
			endPickOptions() {
				const that = this;
				return {
					disabledDate(time) {
						return ''
					}
				}
			},
			//设置时间
			onchangeOff(e) {
				this.timeVal = e
			},
			// 删除
			del(row, tit, num) {
				let delfromData = {
					title: tit,
					num: num,
					url: `product/rule/del/${row.id}`,
					method: "DELETE",
					ids: '',
				};
				this.$modalSure(delfromData)
					.then((res) => {
						this.$Message.success(res.msg);
						this.tableList.splice(num, 1);
						if (!this.tableList.length) {
							this.artFrom.page =
								this.artFrom.page == 1 ? 1 : this.artFrom.page - 1;
						}
						this.getDataList();
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			formatTimeNative(timestamp) {
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
			addPackage() {
				this.$refs.addpackage.ids = 0;
				this.$refs.addpackage.modal = true;
			},
			// 编辑
			edit(row) {
				// this.$refs.addattr.ids = row.id;
				this.$refs.addpackage.modal = true;
				this.$refs.addpackage.getIofo(row);
			},
			// 列表；
			getDataList() {
				this.loading = true;
				if (this.timeVal) {
					this.artFrom.date = this.timeVal
				};
				packageStockListApi(this.artFrom)
					.then((res) => {
						let data = res.data;
						this.tableList = data.list
						this.total = res.data.count;
						this.loading = false;
					})
					.catch((res) => {
						this.loading = false;
						this.$Message.error(res.msg);
					});
			},
			pageChange(status) {
				this.artFrom.page = status;
				this.getDataList();
			},
			// 表格搜索
			userSearchs() {
				this.artFrom.page = 1;
				this.getDataList();
			},
			async exportStock() {
				try {
					this.exportLoading = true;
					let res; // 在函数作用域声明
					// 1. 调用导出接口获取文件信息
					res = await exportPackageStockList(this.artFrom);
					// 2. 检查响应是否成功
					if (res.code !== 0) {
						throw new Error(res.msg || '导出失败');
					}

					// 3. 获取文件信息
					const fileInfo = res.data;

					// 4. 使用文件URL下载文件
					await this.downloadFile(fileInfo);

					// 5. 显示成功消息
					Message.success('导出成功，文件已开始下载');

				} catch (error) {
					// 错误处理
					Message.error(error.message || '导出失败，请重试');
					console.error('导出错误:', error);
				} finally {
					this.exportLoading = false;
				}
			},
			async downloadFile(fileInfo) {
				try {
					// 1. 创建下载链接（优先使用 download_url，再使用 exports_url）
					// const downloadUrl = fileInfo.download_url || fileInfo.exports_url;
					const downloadUrl = fileInfo.exports_url;
					// 2. 创建隐藏的<a>标签触发下载
					const link = document.createElement('a');
					link.href = downloadUrl;

					// 从URL中提取文件名，或自定义文件名
					const fileName = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
					link.download = fileName; // 设置下载文件名

					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
				} catch (error) {
					console.error('文件下载错误:', error);
					throw new Error('文件下载失败: ' + error.message);
				}
			},
		},
	};
</script>

<style scoped lang="stylus">
	.ivu-mts {
		/deep/.ivu-card-body {
			padding-bottom 0 !important padding-top 24px !important
		}
	}

	.input-add {
		width: 250px;
		margin-right: 14px;
	}

	/deep/.ivu-table-header {
		// overflow visible
	}

	/deep/.ivu-table th {
		overflow: visible;
	}

	/deep/.select-item:hover {
		background-color: #f3f3f3;
	}

	/deep/.select-on {
		display: block;
	}

	/deep/.select-item.on {
		// background: #f3f3f3;
	}
</style>